<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 红树林
 -->
<template>
  <div>
    <van-form class="mangrove">
      <van-field
        v-model="ruleForm.mobile"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <div class="popup-open__form-code">
        <van-field v-model="ruleForm.dcode" type="tel" label="验证码" placeholder="请填写验证码" clearable>
            <template #button>
                <van-button size="small" type="primary" @click="createdCode">{{ dcode }}</van-button>
            </template>
        </van-field>
      </div>
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onLogin">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>
  </div>
</template>

<script>
import { alertMsg } from "@/utils/index";
export default {
  name: "Mangrove",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      ruleForm: {
        mobile: "18458358730",
        password: "123456",
        dcode: ""
      },
      dcode: "",
      imageSrc: "",
      IntervalTime: 3,
      type: "0",
      startFlag: false,
      timer: null,
      returnContent: [],
      activeIndex: "",
      isAcceptSuc: false,
      token: "",
      taobaoAccount: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 48 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 48 && this.index !== "") {
        this.createdCode();
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.mobile = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.type = this.item.type || "0";
        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 48 && this.index !== "") {
      this.createdCode();
      this.activeIndex = this.index;
      // 获取保存账号信息
    //   this.ruleForm.mobile = this.item.user;
    //   this.ruleForm.user_pass = this.item.pass;
    //   this.type = this.item.type || "0";
    }
  },
  methods: {
    // 获取验证码
    createdCode() {
      for (
        var A = 4,
          e = [],
          t = "abcdefhijkmnprstwxyzQAZWSXEDCRFVTGBYHNUJMIKOLP0123456789",
          r = t.length,
          g = 0;
        g < A;
        g++
      ) {
        var f = [
          Math.round(220 * Math.random()),
          Math.round(240 * Math.random()),
          Math.round(200 * Math.random())
        ];
        e.push({
          code: t.charAt(Math.floor(Math.random() * r)),
          color: "rgb(" + f + ")",
          fontSize: +[Math.floor(10 * Math.random())] + 6 + 10 + "px",
          padding: [Math.floor(10 * Math.random())] + "px",
          transform:
            "rotate(" +
            (Math.floor(90 * Math.random()) - Math.floor(90 * Math.random())) +
            "deg)"
        });
      }
      this.dcode = e
        .map(function(A) {
          return A.code;
        })
        .join("");
    },
    getStyle(A) {
      return (
        "color: " +
        A.color +
        "; font-size: " +
        A.fontSize +
        "; padding: " +
        A.padding +
        "; transform: " +
        A.transform
      );
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.returnContent = [];
        this.startFlag = true;
        this.returnContent.unshift(alertMsg("正在登录"));
        this.$ajax({
          url: "http://pk.guaxiaogua.cn/api/v1/users/login",
          type: "POST",
          ajaxData: {
            values: this.ruleForm
          },
          returnAll: false,
          dataType: "json",
          headers: {
            "Content-Type": "application/json",
            "X-Requested-With": "XMLHttpRequest"
          },
          method: function(res) {
            _this.returnContent.unshift(alertMsg(res.msg));
            if (res.code === 1) {
              // 登录成功
              _this.token = res.data.token;
              _this.onGetAccountInfo(_this);
            } else {
              _this.startFlag = false;
            }
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 获取账户信息
    onGetAccountInfo(_this) {
      clearInterval(_this.timer);
      _this.$ajax({
        url: "http://pk.guaxiaogua.cn/api/v1/users/getuserinfo",
        type: "get",
        ajaxData: {
          values: this.ruleForm
        },
        returnAll: false,
        dataType: "json",
        headers: {
          "Content-Type": "application/json",
          "X-Requested-With": "XMLHttpRequest",
          Authorization: "Auth " + _this.token
        },
        method: function(res) {
          _this.returnContent.unshift(alertMsg(res.msg));
          if (res.code === 1) {
            // 获取用户信息成功
            _this.taobaoAccount = res.data.taobaoAccount;
          } else {
            _this.timer = setInterval(() => {
              _this.onGetAccountInfo(_this);
            }, _this.IntervalTime * 1000);
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>